package wci.backend.interpreter.executors;

import java.util.List;

import wci.backend.interpreter.Executor;
import wci.intermediate.ICodeNode;

/**
 * <h1>IfExecutor</h1>
 * <p>执行IF语句逻辑</p>
 * <p>Copyright (c) 2009 by Ronald Mak</p>
 * <p>For instructional purposes only.  No warranties.</p>
 */
public class IfExecutor extends StatementExecutor
{
    public IfExecutor(Executor parent)
    {
        super(parent);
    }
    public Object execute(ICodeNode node)
    {
        //记住IF有两个或者三个节点
        List<ICodeNode> children = node.getChildren();
        ICodeNode exprNode = children.get(0);
        ICodeNode thenStmtNode = children.get(1);
        ICodeNode elseStmtNode = children.size() > 2 ? children.get(2) : null;
        //判别式和语句主体
        ExpressionExecutor expressionExecutor = new ExpressionExecutor(this);
        StatementExecutor statementExecutor = new StatementExecutor(this);
        //算一下IF表达式
        boolean b = (Boolean) expressionExecutor.execute(exprNode);
        if (b) {
            statementExecutor.execute(thenStmtNode);
        }
        else if (elseStmtNode != null) {
            statementExecutor.execute(elseStmtNode);
        }
        ++executionCount;//if虽然可能后好几句，但是只可能执行一句。 
        return null;
    }
}
